import { createAlova } from 'alova'
import uniappAdapter from '@alova/adapter-uniapp'
import { decrypt, encrypt } from './crypto'

const BASE_URL = import.meta.env.VITE_APP_URL
// 再创建一个实例,无需加解密,用作AI请求
const BASE_AI_URL = import.meta.env.VITE_APP_AI_URL

export const alovaInst = createAlova({
  baseURL: BASE_URL,
  timeout: 15000,
  ...uniappAdapter(),
  beforeRequest: (method) => {
    console.log('method', method)

    // 这里可以统一设置 token
    const token = uni.getStorageSync('token')
    if (token) {
      method.config.headers = {
        ...method.config.headers,
        Authorization: `Bearer ${token}`
      }
    }

    // 接口加密
    if (method.config.params || method.data) {
      if (method.type === 'GET') {
        method.config.params = encrypt(method.config.params)
      } else {
        method.data = encrypt(method.data)
      }
    }
  },
  responded: {
    onSuccess: (response: any) => {
      // response 是 uniapp 的 response
      const { data } = response
      if (data.code !== 200) {
        uni.showToast({ title: data.message || '请求失败', icon: 'none' })
        throw new Error(data.message)
      }
      return decrypt(data)
    },
    onError: (err) => {
      uni.showToast({ title: '网络错误', icon: 'none' })
      throw err
    }
  }
})

// AI服务
export const alovaAiInst = createAlova({
  baseURL: BASE_AI_URL,
  timeout: 15000,
  ...uniappAdapter(),
  beforeRequest: (method) => {
    console.log('method', method)

    method.config.headers = {
      ...method.config.headers,
      'Content-Type': 'application/json',
      Authorization: `Bearer ${import.meta.env.VITE_APP_AI_KEY}`,
      appid: import.meta.env.VITE_APP_AI_APP_ID
    }
    const { text } = method.data
    // 百度千帆
    method.data = {
      model: import.meta.env.VITE_APP_AI_MODEL,
      messages: [
        {
          role: 'user',
          content: [
            {
              type: 'text',
              text
            }
          ]
        }
      ],
      web_search: {
        enable: false,
        enable_citation: false,
        enable_trace: false
      },
      plugin_options: {}
    }
  },
  responded: {
    onSuccess: (response: any) => {
      const { data } = response
      console.log('data', data)
      return data
    },
    onError: (err) => {
      console.log('err', err)
      uni.showToast({ title: '网络错误', icon: 'none' })
      throw err
    }
  }
})

class Request {
  async GET<T extends object>(data: IRequestParams<T>): Promise<any> {
    return alovaInst.Get(data.url, {
      params: data.params
    })
  }
  async POST<T extends object, R = any>(data: IRequestParams<T>): Promise<R> {
    return alovaInst.Post<R>(data.url, data.params)
  }
}

export const request = new Request()
